from django.contrib import admin
from coupon.models import CouponModel,CouponCourseModel,CouponCourseCategoryModel,CouponCourseDirectionModel,CouponLogModel
from django_redis import get_redis_connection
import json

# Register your models here.

# 方向
class CouponDirectionInline(admin.TabularInline):
    model = CouponCourseDirectionModel
    fields = ['id','direction']

# 分类
class CouponCategoryInline(admin.TabularInline):
    model = CouponCourseCategoryModel
    fields = ['id','category']

# 分类
class CouponCourseInline(admin.TabularInline):
    model = CouponCourseModel
    fields = ['id','course']


# 优惠券
class CouponModelAdmin(admin.ModelAdmin):
    list_display = ['id','name','start_time',"end_time",'total','has_total',"coupon_type",'get_type']
    inlines = [CouponDirectionInline,CouponCategoryInline,CouponCourseInline]

admin.site.register(CouponModel,CouponModelAdmin)


class CouponLogModelAdmin(admin.ModelAdmin):
    list_display = ['id','user','coupon','use_time','use_status']

    def save_model(self, request, obj, form, change):
        
        obj.save()

        redis = get_redis_connection('coupon')

        if obj.use_status == 0 and obj.use_time == None:
            pipe = redis.pipeline()
            pipe.multi()

            coupon_dict = {
                "coupon_id":obj.coupon.id,
                "name":obj.coupon.name,
                "discount":obj.coupon.discount,
                "get_discount_display":obj.coupon.get_discount_display(),
                "coupon_type":obj.coupon.coupon_type,
                "get_coupon_type_display":obj.coupon.get_coupon_type_display(),
                "get_type":obj.coupon.get_type,
                "get_get_type_display":obj.coupon.get_get_type_display(),
                "start_time":obj.coupon.start_time.strftime("%Y-%m-%d %H:%M:%S"),
                "end_time": obj.coupon.end_time.strftime("%Y-%m-%d %H:%M:%S"),
                "condition":obj.coupon.condition,
                "sale":obj.coupon.sale,
                "to_direction":json.dumps(list(obj.coupon.to_direction.values('direction__id','direction__name'))),
                "to_category":json.dumps(list(obj.coupon.to_category.values('category__id','category__name'))),
                "to_course":json.dumps(list(obj.coupon.to_course.values('course__id','course__name'))),
            }
            pipe.hset(f"{obj.user.id}:{obj.id}",mapping=coupon_dict)

            print('存入redis中的数据的key')
            print(f"{obj.user.id}:{obj.id}")
            from datetime import datetime
            # setex()
            # 根据key值，设置过期时间
            pipe.expire(f"{obj.user.id}:{obj.id}",  int(obj.coupon.end_time.timestamp() - datetime.now().timestamp()))
            pipe.execute()
        else:
            redis.delete(f"{obj.user.id}:{obj.id}")

    def delete_model(self, request, obj):
        redis = get_redis_connection('coupon')
        redis.delete(f"{obj.user.id}:{obj.id}")
        obj.delete()
    def delete_queryset(self, request, queryset):
        redis = get_redis_connection('coupon')
        for qs in queryset:
            redis.delete(f"{qs.user.id}:{qs.id}")
        queryset.delete()


admin.site.register(CouponLogModel,CouponLogModelAdmin)













